package com.i2works.smartluolong.web.controller.common;

import com.alibaba.fastjson.JSONObject;
import com.i2works.smartluolong.utils.base.GlobalConstant;
import com.i2works.smartluolong.utils.basecommon.BaseUploadController;
import com.i2works.smartluolong.utils.common.FileBase64ConvertUitl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * 上传
 *
 * @author Liu Yutao
 * @className UploadUtil
 * @email koal@vip.qq.com
 * @date 2016/2/12 22:47
 */

@Controller
@RequestMapping(value = "/common/uploader")
public class UploadController extends BaseUploadController {

    /**
     * 上传
     *
     * @param files     文件
     * @param filesType 文件类型（0头像图片，1详情附件）
     */
    @PostMapping("/index")
    @ResponseBody
    @Override
    public JSONObject index(
            @RequestParam(value = "files", required = false) MultipartFile[] files,
            @RequestParam(value = "filesType", required = false) Integer filesType
    ) {
        return super.index(files, filesType);
    }


    /**
     * 上传BASE64
     *
     * @param files     文件
     * @param filesType 文件类型（0头像图片，1详情附件）
     */
    @PostMapping("/base64")
    @ResponseBody
    public JSONObject base64(@RequestParam(value = "base64Code") String base64Code) {
        int indexOf = base64Code.indexOf("data:image/");
        //-1不存在，就添加前缀，0存在，就不需要添加了。
        if (indexOf == -1) {
            base64Code = GlobalConstant.base64Prefix.JPG + base64Code.trim().replaceAll("\\s*", "");
        }
        base64Code = base64Code.trim().replaceAll("\\s*", "");
        MultipartFile multipartFile = FileBase64ConvertUitl.base64ToMultipart(base64Code);
        MultipartFile[] multipartFiles = new MultipartFile[1];
        multipartFiles[0] = multipartFile;
        return super.index(multipartFiles, GlobalConstant.fileType.IMAGE);
    }
}
